<template>
	<view class="nas-search-content">
		<view class="nas-search" v-if="!showBottomMore">
			<image src="/static/nas-static/nas_back_s.svg" mode="" @click="goBack"></image>
			<u-search v-model="content" :clearabled="true" @custom="goSearch" @search="goSearch"></u-search>
		</view>

		<view class="nas-search-top" v-if="showBottomMore">
			<view class="nas-bar-item" @click="allCancel">取消</view>
			<view class="nas-bar-item">已选中{{ selectAmount }}个文件</view>
			<view class="nas-bar-item" @click="allSelect">全选</view>
		</view>

		<view class="nas-search-body">
			<view class="nas-search-body-item" v-for="(item, index) in fileList" :key="index" @click="goIntoFile(item)" :class="{ active: item.select }">
				<view class="nas-search-body-image"><image :src="item.url" mode=""></image></view>
				<view class="nas-search-body-left-right">
					<view>{{ item.filename }}</view>
					<view>{{ happenTimeFun(item.filetime) }} {{ dealSize(item.filesize) }}</view>
				</view>
				<view class="nas-search-body-right-circle" @click.stop="hasSelectFile(item)">
					<image v-if="!item.select" src="/static/nas-static/nas-radio-none.svg" mode=""></image>
					<image v-if="item.select" src="/static/nas-static/nas-radio-yes.svg" mode=""></image>
				</view>
			</view>
		</view>
		<!-- 更多底部上拉层 -->
		<u-popup v-model="showMore" bgColor="#fff" mode="bottom" style="z-index: 999;">
			<view class="nas-popup-bottom-item" @click="goMore('重命名')" v-if="canRename">
				<image src="/static/nas-static/nas-rename.svg" mode=""></image>
				<view>重命名</view>
			</view>
			<view class="nas-popup-bottom-item" @click="goMore('家庭圈')">
				<image src="/static/nas-static/nas-jiating.svg" mode=""></image>
				<view>分享到家庭圈</view>
			</view>
			<view class="nas-popup-bottom-item" @click="goMore('云空间')">
				<image src="/static/nas-static/nas-geren.svg" mode=""></image>
				<view>分享到云空间</view>
			</view>
		</u-popup>

		<!-- 更多操作 -->
		<view class="nas-more-bottom" v-if="showBottomMore">
			<view class="nas-more-bottom-item" @click="dealBottom('download')">
				<image class="nas-more-bottom-img" src="/static/nas-static/nas-download.svg"></image>
				<view>下载</view>
			</view>
			<view class="nas-more-bottom-item" @click="dealBottom('move')">
				<image class="nas-more-bottom-img" src="/static/nas-static/nas-yidong.svg"></image>
				<view>移动</view>
			</view>
			<view class="nas-more-bottom-item" @click="dealBottom('delete')">
				<image class="nas-more-bottom-img" src="/static/nas-static/nas-delete.svg"></image>
				<view>删除</view>
			</view>
			<view class="nas-more-bottom-item" @click="dealBottom('copy')">
				<image class="nas-more-bottom-img" src="/static/nas-static/nas-copy.svg"></image>
				<view>复制</view>
			</view>
			<view class="nas-more-bottom-item" @click="openMore">
				<image class="nas-more-bottom-img" src="/static/nas-static/nas-showmore.svg"></image>
				<view>更多</view>
			</view>
		</view>

		<!-- 重命名弹窗 -->
		<u-modal v-model="showRename" title="重命名" :showCancelButton="true" @confirm="goRename">
			<view class="nas-content"><uni-easyinput v-model="newName" :clearable="true"></uni-easyinput></view>
		</u-modal>
		<!-- 删除弹框 -->
		<u-modal v-model="showDelete" title="删除文件" :showCancelButton="true" @confirm="deleteFiles"><view class="nas-content">确认删除么？</view></u-modal>
	</view>
</template>

<script>
import request from '../utils/request.js';
import NasDownload from '../utils/download.js';
import { mapMutations } from 'vuex';
export default {
	data() {
		return {
			content: '',
			fileList: [],
			pageNum: 1,
			showBottomMore: false, // 底部操作栏
			showRename: false, // 重命名弹窗
			newName: '', // 新的命名
			canRename: false, // 是否可以重命名
			showCreateFile: false, // 新建文件夹弹窗
			createFileName: '', // 新建的文件夹名称
			triggered: false, // 出发下拉刷新
			isOpenRefresh: true, // 是否开启下拉
			showDelete: false, // 删除确认框
			selectAmount: 0,
			showMore: false
		};
	},
	onReachBottom() {
		//上拉触底函数
		// if (!this.isLoadMore) {
		// 	//此处判断，上锁，防止重复请求
		// 	this.isLoadMore = true;
		// 	this.pageNum += 1;
		// 	this.getVideoList();
		// }
	},
	onLoad() {
		// 通知刷新数据
		uni.$on('refreshData', () => {
			this.goSearch();
		});
	},
	methods: {
		...mapMutations(['nasDownloadListAdd']),
		async goSearch() {
			if (!this.content) {
				uni.showToast({
					title: '请输入搜索内容',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			this.showMore = false;
			this.showBottomMore = false;
			const params = {
				method: 'POST',
				url: '/nas/rd_center/data/get',
				data: {
					method: 'capacity.nas.cloud.volume.find',
					type: 1,
					data: {
						directory: '/',
						key: this.content,
						limit: '100'
					}
				}
			};
			// console.log(params, 'params');
			const res = await request(params);
			res.data.data.forEach(val => {
				val.select = false;
				val.url = this.getFileType(val.filename);
			});
			this.fileList = res.data.data;
			console.log(res, 'res');
		},
		goBack() {
			uni.navigateBack({
				delta: 1
			});
		},
		// 确认删除
		async deleteFiles() {
			const selectList = this.fileList.filter(val => val.select);
			for (let i = 0; i < selectList.length; i++) {
				const params = {
					method: 'POST',
					url: '/nas/rd_center/data/get',
					data: {
						method: 'capacity.nas.cloud.file.dir.delete',
						type: 1,
						data: {
							directory: selectList[i].filepath + selectList[i].filename
						}
					}
				};
				const res = await request(params);
			}
			// 重新获取列表数据
			this.goSearch();
		},
		// 重命名
		async goRename() {
			if (!this.newName) return;
			const file = this.fileList.find(val => val.select);
			let fileList = file.filepath.split('/');
			fileList.pop();
			const params = {
				method: 'POST',
				url: '/nas/rd_center/data/get',
				data: {
					method: 'capacity.nas.cloud.file.rename',
					type: 1,
					data: {
						directory: fileList.join('/') == '' ? '/' : fileList.join('/'),
						filename: file.filename,
						newFilename: this.newName
					}
				}
			};
			console.log(params, '重命名的params');
			const res = await request(params);
			// 重新获取列表数据
			this.goSearch();
		},
		// 打开更多窗口
		openMore() {
			this.showMore = true;
			// this.$refs.nasPopupMore.open('bottom');
		},
		// 更多操作方法
		goMore(type) {
			switch (type) {
				case '重命名':
					this.$refs.nasPopupMore.close();
					this.newName = this.fileList.find(val => val.select).filename;
					this.showRename = true;
					break;
				case '家庭圈':
					// 处理分享到家庭圈
					const familyFileInfos = {
						fileList: [],
						dirList: []
					};
					this.fileList.forEach(pre => {
						if (pre.select) {
							// 保存文件
							familyFileInfos.fileList.push(pre.filepath + pre.filename);
						}
					});
					const familyInfos = JSON.stringify(familyFileInfos);
					uni.navigateTo({
						url: `/pages/nas/nas-family/nas-family?infos=${familyInfos}`
					});
					break;
				case '云空间':
					// 处理分享到云空间
					const yunFileInfos = {
						fileList: [],
						dirList: []
					};
					this.fileList.forEach(pre => {
						if (pre.select) {
							// 保存文件夹
							if (pre.type === 'DIR') {
								yunFileInfos.dirList.push({
									dirId: pre.path + pre.filename + '/',
									dirName: pre.filename
								});
							} else {
								// 保存文件
								yunFileInfos.fileList.push(pre.path + pre.filename);
							}
						}
					});
					const yunInfos = JSON.stringify(yunFileInfos);
					uni.navigateTo({
						url: `/pages/nas/nas-saveUploadFile/nas-saveUploadFile?type=5&familyInfos=${yunInfos}`
					});
					break;
				default:
					break;
			}
		},
		// 底部操作
		dealBottom(type) {
			switch (type) {
				case 'delete':
					this.showDelete = true;
					break;
				case 'move':
					// 获取文件当前的文件路径
					let moveList = [];
					this.fileList.forEach(pre => {
						if (pre.select) {
							const pathName = `${pre.filepath}${pre.filename}`;
							moveList.push(pathName);
						}
					});
					const directorys = JSON.stringify(moveList);
					uni.navigateTo({
						url: `/pages/nas/nas-saveUploadFile/nas-saveUploadFile?type=1&directorys=${directorys}`
					});
					break;
				case 'copy':
					// 获取文件当前的文件路径
					let copyList = [];
					this.fileList.forEach(pre => {
						if (pre.select) {
							const pathName = `${pre.filepath}${pre.filename}`;
							copyList.push(pathName);
						}
					});
					const directorysCopy = JSON.stringify(copyList);
					uni.navigateTo({
						url: `/pages/nas/nas-saveUploadFile/nas-saveUploadFile?type=3&directorys=${directorysCopy}`
					});
					break;
				case 'download':
					// 文件夹不支持下载
					const hasDir = this.fileList.some(ped => ped.select && ped.type === 'DIR');
					if (hasDir) {
						uni.showToast({
							title: '文件夹暂不支持下载',
							icon: 'none',
							duration: 2000
						});
					} else {
						const downloadList = this.fileList.forEach(val => {
							if (val.select) {
								// 处理参数
								const item = {
									filenamepath: val.filepath + val.filename, //下载的目标文件夹目录
									name: val.filename, //文件名
									size: val.filesize, //文件的总大小
									uid: 'nas_' + this.uuid() //唯一的标识
								};
								let nasDownload = new NasDownload.nasDownloadClass({
									...item
								});
								// console.log(nasDownload, 'nasDownload');
								this.nasDownloadListAdd(nasDownload);
							}
						});
						this.fileList.forEach(pre => (pre.select = false));
						this.showBottomMore = false;
						uni.showToast({
							title: '已加入下载列表',
							icon: 'none',
							duration: 2000
						});
					}
					break;
				default:
					break;
			}
		},
		// 取消选择
		allCancel() {
			this.fileList.forEach(val => (val.select = false));
			this.showBottomMore = false;
		},
		// 全选
		allSelect() {
			this.fileList.forEach(val => (val.select = true));
		},
		// 判断文件的类型
		getFileType(filename) {
			let previewUrl = '';
			let arr = filename.split('.');
			let len = arr.length;
			let ext = arr[len - 1].toLocaleLowerCase();
			if (ext == 'mp3') {
				// 音频
				previewUrl = '/static/nas-static/nas-new-music.png';
			}
			if (ext == 'doc' || ext == 'docx') {
				previewUrl = '/static/nas-static/nas-new-file.png';
			}
			if (ext == 'ppt' || ext == 'pptx') {
				previewUrl = '/static/nas-static/nas-new-file.png';
			}
			if (ext == 'pdf') {
				previewUrl = '/static/nas-static/nas-new-file.png';
			}
			if (ext == 'rar' || ext == 'zip' || ext == '7z' || ext == 'gz') {
				previewUrl = '/static/nas-static/nas-zip.svg';
			}
			if (ext == 'xls' || ext == 'xlsx') {
				previewUrl = '/static/nas-static/nas-new-file.png';
			}
			if (ext == 'txt') {
				previewUrl = '/static/nas-static/nas-new-file.png';
			}
			if (ext == 'mp4' || ext == 'mov') {
				previewUrl = '/static/nas-static/nas-new-video.png';
			}
			if (ext == 'jpg' || ext == 'png' || ext == 'jpeg') {
				previewUrl = '/static/nas-static/nas-new-pic.png';
			}
			if (previewUrl) {
				return previewUrl;
			} else {
				return '/static/nas-static/nas-new-pic.png';
			}
		},
		// 判断是否存在选中的文件
		hasSelectFile(item) {
			item.select = !item.select;
			const hasSelectFileList = this.fileList.filter(val => val.select);
			this.selectAmount = hasSelectFileList.length;
			// 多选文件不可以重命名
			if (hasSelectFileList.length > 1) {
				this.showBottomMore = true;
				this.canRename = false;
			} else if (hasSelectFileList.length === 1) {
				// 单选文件可以重命名
				this.showBottomMore = true;
				this.canRename = true;
			} else {
				this.showBottomMore = false;
				this.canRename = false;
			}
		},
		goIntoFile(item) {
			if (!this.showBottomMore) {
				// 打开文件
				const filename = item.filename;
				const filenamepath = item.filepath + item.filename; //上传到的目标文件夹目录
				// console.log(filenamepath ,'filenamepath')
				uni.navigateTo({
					url: `/pages/nas/nas-video/nas-video?filename=${filename}&filenamepath=${filenamepath}`
				});
			}
		},
		//计算文件的大小
		dealSize: num => {
			if (!num) return '0B';
			let k = 1024; //设定基础容量大小
			let sizeStr = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; //容量单位
			let i = 0; //单位下标和次幂
			for (let l = 0; l < 8; l++) {
				//因为只有8个单位所以循环八次
				if (num / Math.pow(k, l) < 1) {
					//判断传入数值 除以 基础大小的次幂 是否小于1，这里小于1 就代表已经当前下标的单位已经不合适了所以跳出循环
					break; //小于1跳出循环
				}
				i = l; //不小于1的话这个单位就合适或者还要大于这个单位 接着循环
			}
			//例： 900 / Math.pow(1024, 0)  1024的0 次幂 是1 所以只要输入的不小于1 这个最小单位就成立了；
			//   900 / Math.pow(1024, 1)  1024的1次幂 是1024  900/1024 < 1 所以跳出循环 下边的 i = l；就不会执行  所以 i = 0； sizeStr[0] = 'B';
			//   以此类推 直到循环结束 或 条件成立
			return (num / Math.pow(k, i)).toFixed(2) + sizeStr[i]; //循环结束 或 条件成立 返回字符
		},
		//时间戳数据处理
		happenTimeFun(num) {
			let date = new Date(num * 1000);
			//时间戳为10位需*1000，时间戳为13位的话不需乘1000
			let y = date.getFullYear();
			let MM = date.getMonth() + 1;
			MM = MM < 10 ? '0' + MM : MM; //月补0
			let d = date.getDate();
			d = d < 10 ? '0' + d : d; //天补0
			let h = date.getHours();
			h = h < 10 ? '0' + h : h; //小时补0
			let m = date.getMinutes();
			m = m < 10 ? '0' + m : m; //分钟补0
			let s = date.getSeconds();
			s = s < 10 ? '0' + s : s; //秒补0
			return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
		},
		//生成随机数
		uuid() {
			let len = 8; //长度
			let radix = 8; //基数
			let chars = 'GHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
			let uuid = [],
				i;
			radix = radix || chars.length;
			if (len) {
				for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
			} else {
				let r = null;
				uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
				uuid[14] = '4';
				for (i = 0; i < 36; i++) {
					if (!uuid[i]) {
						r = 0 | (Math.random() * 16);
						uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
					}
				}
			}
			return uuid.join('');
		}
	}
};
</script>

<style lang="scss" scoped>
.nas-search-content {
	position: relative;
	height: 100%;
	background: #fff;
	.nas-search {
		position: absolute;
		top: 98rpx;
		left: 0;
		right: 0;
		height: 48rpx;
		padding: 0rpx 32rpx 0 32rpx;
		display: flex;
		align-items: center;
		image {
			width: 50rpx;
			height: 34rpx;
			margin-right: 14rpx;
		}
	}
	.nas-search-top {
		position: absolute;
		background: #ffffff;
		top: 98rpx;
		left: 0;
		right: 0;
		height: 48rpx;
		width: 100%;
		display: flex;
		image {
			width: 50rpx;
			height: 34rpx;
			margin-right: 14rpx;
		}
		.nas-bar-item {
			flex: 1;
			&:nth-of-type(1) {
				display: flex;
				align-items: center;
				margin-left: 32rpx;
				color: #3069dc;
				image {
					width: 50rpx;
					height: 34rpx;
				}
			}
			&:nth-of-type(2) {
				text-align: center;
				ont-family: HarmonyOS_Sans_SC_Medium;
				font-size: 34rpx;
				color: rgba(51, 51, 51, 0.9);
				font-weight: 500;
			}
			&:last-of-type {
				text-align: right;
				margin-right: 32rpx;
				font-family: HarmonyOS_Sans_SC;
				font-size: 28rpx;
				color: #3069dc;
				font-weight: 400;
			}
		}
	}

	.nas-search-body {
		position: absolute;
		top: 190rpx;
		left: 0;
		right: 0;
		bottom: 0;
		overflow-y: scroll;
	}
	.nas-popup-bottom-item {
		padding: 22rpx 32rpx 22rpx 32rpx;
		height: 110rpx;
		display: flex;
		align-items: center;
		font-family: HarmonyOS_Sans_SC;
		font-size: 28rpx;
		color: #333333;
		font-weight: 400;
		image {
			width: 36rpx;
			height: 34rpx;
			margin-right: 16rpx;
		}
		&.active {
			color: #3069dc;
		}
		&:first-of-type {
			margin-bottom: 0rpx;
		}
		&:nth-of-type(2) {
			border-top: 1rpx solid #d8d8d8;
		}
		&:last-of-type {
			margin-top: 0rpx;
			border-top: 1rpx solid #d8d8d8;
		}
	}
	.nas-more-bottom {
		position: absolute;
		left: 0;
		right: 0;
		bottom: 0;
		height: 150rpx;
		background: #3069dc;
		border-radius: 16rpx;
		padding-top: 20rpx;
		display: flex;
		justify-content: space-around;
		.nas-more-bottom-item {
			width: 84rpx;
			font-family: HarmonyOS_Sans_SC;
			font-size: 28rpx;
			color: rgba(255, 255, 255, 0.9);
			text-align: center;
			font-weight: 500;
			.nas-more-bottom-img {
				width: 32rpx;
				height: 36rpx;
			}
		}
	}
	.nas-content {
		padding: 32rpx;
		text-align: center;
		font-family: HarmonyOS_Sans_SC;
		font-size: 28rpx;
		color: #808080;
		letter-spacing: 0;
		font-weight: 400;
	}
}

.nas-search-body-item {
	padding: 26rpx 32rpx 26rpx 32rpx;
	// height: 130rpx;
	display: flex;
	align-items: center;
	&.active {
		background-color: rgba(246, 236, 236, 0.3);
	}
	.nas-search-body-image {
		display: flex;
		align-items: center;
		image {
			width: 62rpx;
			height: 62rpx;
		}
	}
	.nas-search-body-left-right {
		margin-left: 16rpx;
		view {
			max-width: 480rpx;
			&:first-of-type {
				font-family: HarmonyOS_Sans_SC;
				font-size: 28rpx;
				color: #333333;
				letter-spacing: 0;
				font-weight: 400;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
			}
			&:last-of-type {
				font-family: HarmonyOS_Sans_SC;
				font-size: 24rpx;
				color: #999999;
				letter-spacing: 0;
				font-weight: 400;
			}
		}
	}
	.nas-search-body-right-circle {
		margin-left: auto;
		width: 38rpx;
		height: 38rpx;
		image {
			width: 38rpx;
			height: 38rpx;
		}
	}
}
</style>
